package com.example.esp8266.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.esp8266.R;
import com.example.esp8266.activity.fragment.CommonFragment;
import com.example.esp8266.activity.fragment.ExpertFragment;
import com.example.esp8266.activity.fragment.LogPrintFragment;
import com.example.esp8266.activity.utile.MouthpieceTool;
import com.example.esp8266.activity.utile.SocketLink;
import com.example.esp8266.activity.wifi.WifiActivity;
import com.example.esp8266.activity.wifi.WifiUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    BottomNavigationView bottomNavigationView;
    private int connectState=0;
    private  SocketLink socketLink;
    public SocketLink getSocketLink() {
        return socketLink;
    }
    public void setSocketLink(SocketLink socketLink) {
        this.socketLink = socketLink;
    }
    FloatingActionButton floatingActionButton;
    private AlertDialog dialog;

    private MouthpieceTool mouthpieceTool;
    public MouthpieceTool getMouthpieceTool() {
        return mouthpieceTool;
    }
    public void setMouthpieceTool(MouthpieceTool mouthpieceTool) {
        this.mouthpieceTool = mouthpieceTool;
    }
    private String linkTimeResult;
    TextView linkBoardTimeTv;

    private static final int WRITE_COARSE_LOCATION_REQUEST_CODE = 0;//定位权限
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        socketLink = new SocketLink();
        mouthpieceTool = new MouthpieceTool();
//        connectState=1;
        bottomNavigationView = findViewById(R.id.bottomConfig);
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction().replace(R.id.frameConfig,new CommonFragment()).commit();
        }
        bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment fragment = null;
                switch (item.getItemId()){
                    case R.id.common_config: // 普通配置
                        fragment = new CommonFragment();
                        break;
//                    case R.id.expert_config: // 高级配置
//                        fragment = new ExpertFragment();
//                        break;
//                    case R.id.log_print: //日志打印
//                        fragment = new LogPrintFragment();
//                        break;
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.frameConfig,fragment).commit();
                return true;
            }
        });
        floatingActionButton = findViewById(R.id.connect);
        floatingActionButton.setOnClickListener(this);
//        linkBoardTimeTv = findViewById(R.id.linkBoardTime_tv);

        if (!EventBus.getDefault().isRegistered(this)) { //判断是否注册，避免重复注册
            EventBus.getDefault().register(this);
        }
        showPermissions(); //开启 动态定位 权限
    }
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.connect:  //连接主板
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("是否连接主板？");
                builder.setIcon(R.drawable.link_ico);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        if (connectState==1){
                        System.out.println("------点击 确定-------");
                            String ip1 = WifiUtil.getWifiIP(getApplicationContext());//192.168.4.3
                            String ip2 = WifiUtil.getWifiRouteIPAddress(getApplicationContext());  //192.168.4.1
                            System.out.println(ip2);
                            socketLink.openSerialPort("192.168.1.1",8888);
                            connectState=0;
//                        }
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.show();
                break;
            default:
                break;
        }
    }
    //接收wifi回传指令
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(String str){
        System.out.println("----MainActivity-------"+str+"------------");

    }
    // 将16进制 ASCII转成字符串
    public static String asciiToString(String str) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < str.length(); i += 2) {
            stringBuilder.append((char) Integer.parseInt(str.substring(i, i + 2), 16));
        }
        return stringBuilder.toString();
    }
    //成功提示弹窗
    public Toast popWindowSuccess(final String content) {
        Toast  toast =  Toast.makeText(MainActivity.this, content,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }
    @Override
    protected void onStart() {
        super.onStart();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
    // Android 6.0 以上的版本 申请定位权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case WRITE_COARSE_LOCATION_REQUEST_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(this, "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
    public void showPermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE
            }, WRITE_COARSE_LOCATION_REQUEST_CODE);
        }
    }
}